package com.xdh.zzqh.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.xdh.zzqh.R
import com.xdh.zzqh.store.User
import com.xdh.zzqh.ui.dialog.CreateUserDialog
import com.xdh.zzqh.utils.onClick
import com.xdh.zzqh.utils.runOnUiWithInit
import com.xdh.zzqh.utils.showToast
import com.xdh.zzqh.utils.stringById

class UserFragment : Fragment() {

    private val mAdapter = UserAdapter()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_user, null)
        initUi(view)
        return view
    }

    private fun initUi(view: View) {
        val btnCreate = view.findViewById<Button>(R.id.id_user_btn_create)
        val rv = view.findViewById<RecyclerView>(R.id.id_user_rv)
        rv.adapter = mAdapter
        rv.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        btnCreate.onClick {

            try {
                val name = CreateUserDialog().waitCreate()
                User(name).save()
                mAdapter.update()
            } catch (e: Exception) {
                e.printStackTrace()
                showToast(e.message ?: stringById(R.string.cuo_wu))
            }
        }
    }

    override fun onResume() {
        super.onResume()
        runOnUiWithInit { mAdapter.update() }
    }
}

private class UserItemView(view: View) : RecyclerView.ViewHolder(view) {

    private val tvName = view.findViewById<TextView>(R.id.id_user_tv_user)
    private val btnDel = view.findViewById<Button>(R.id.id_user_btn_delete)

    fun setUp(name: String, delete: suspend () -> Unit) {
        tvName.text = name
        btnDel.onClick(delete)
    }
}

private class UserAdapter : RecyclerView.Adapter<UserItemView>() {

    private var list = emptyList<String>()

    @SuppressLint("NotifyDataSetChanged")
    suspend fun update() {
        list = User.queryAll()
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: UserItemView, position: Int) {
        val name = list[position]
        holder.setUp(name) {
            User.delete(name)
            update()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserItemView {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_user, parent, false)
        return UserItemView(view)
    }
}


















